package com.java.code.thread;

import org.junit.Test;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantLock;

public class JavaThreadSafety {

    /**
     * 往list里面同步添加数据
     * Vector 和自定义synchronized就暂时不考虑了
     */
    @Test
    public void listAddSafety() {
        List<String> names = new LinkedList<>();
        names.add("sub");
        names.add("jobs");
        // 同步方法1 内部使用lock
        long a = System.currentTimeMillis();
        List<String> strings = new CopyOnWriteArrayList<>(names);
        for (int i = 0; i < 100000; i++) {
            strings.add("param1");
        }
        long b = System.currentTimeMillis();
        // 同步方法2 装饰器模式使用 synchronized
        List<String> synchronizedList = Collections.synchronizedList(names);
        for (int i = 0; i < 100000; i++) {
            synchronizedList.add("param2");
        }
        long c = System.currentTimeMillis();
        System.out.println("CopyOnWriteArrayList time == " + (b - a));
        System.out.println("Collections.synchronizedList time == " + (c - b));
    }


}
